/*
 * @Author: lvye
 * @Description:
 * @Date: 2023-06-29 16:24:56
 * @LastEditTime: 2023-08-21 11:29:06
 * @FilePath: \vue3-ts\src\router\index.ts
 */
import {
  RouteRecordRaw,
  createRouter,
  createWebHashHistory
  // routerKey
} from "vue-router"
import localCache from "@/utils/cache"
import { firstMenu } from "@/utils/map-menu"
const routes: RouteRecordRaw[] = [
  {
    path: "/",
    redirect: "/main"
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/login.vue")
  },
  {
    path: "/main",
    name: "main",
    component: () => import("@/views/main/main.vue")
  },
  {
    path: "/:pathMatch(.*)*",
    name: "notFound",
    component: () => import("@/views/not-found/not-found.vue")
  }
]

//导入生成的路由数据
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.path !== "/login") {
    const token = localCache.getCache("token")
    if (!token) {
      next({
        path: "/login"
      })
    } else {
      if (to.path === "/main") {
        //初始化进入菜单第一项
        next(firstMenu.url)
      } else {
        next()
      }
    }
  } else {
    next()
  }
})
export default router
